<template>
  <div>
    <el-container>
      <el-header style="display:flex;align-items: center;justify-content: space-between;padding: 10px;border-bottom: 1px solid #f2f2f2;">
        <div>
          <svg-icon class="primary" :icon-class="$route.meta.icon" />
          <span class="primary">导入导出</span>
        </div>
      </el-header>
      <div class="pd10">
        <div style="align-items: center;margin: 10px 0; display: flex;justify-content: space-between;">
          <div>
            <!-- <el-date-picker
              v-model="query.date"
              value-format="yyyy-MM-dd"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
            /> -->
            <el-select v-model="query.tagIds" placeholder="请选择要导出的标签" clearable multiple collapse-tags>
              <el-option v-for="item in tags" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-select v-model="query.isMarketable" placeholder="请选择要导出的状态" clearable>
              <el-option label="未上架" :value="false" />
              <el-option label="已上架" :value="true" />
            </el-select>
          </div>
          <div>
            <el-button icon="el-icon-download" :loading="downloadChecked" @click="handleDownload">{{ downloadChecked?'&nbsp&nbsp&nbsp正在导出&nbsp&nbsp&nbsp': '导出商品列表' }}</el-button>
            <el-button icon="el-icon-refresh-right" type="primary" @click="daoruClick">导入商品列表</el-button>
          </div>
        </div>
        <el-table ref="table" :data="showExportData" border stripe :height="curHeight">
          <el-table-column v-if="showError"  label="result" align="center" prop="result" width="60" />
          <el-table-column label="id" align="center" prop="id" width="60" />
          <el-table-column label="货号" align="left" prop="sn" width="100" />
          <el-table-column label="品名" align="left" prop="name" min-width="250" />
          <el-table-column label="规格1" align="left" prop="spec1" min-width="200" />
          <el-table-column label="规格2" align="left" prop="spec2" min-width="200" />
          <el-table-column label="市场价" align="right" prop="marketPrice" width="80" />
          <el-table-column label="销售价" align="right" prop="price" width="80" />
          <el-table-column label="单位" align="right" prop="unit" width="80" />
          <el-table-column label="库存" align="right" prop="stock" width="80" />
          <el-table-column label="VIP1价" align="right" prop="vip1price" width="80" />
          <el-table-column label="VIP2价" align="right" prop="vip2price" width="80" />
          <el-table-column label="VIP3价" align="right" prop="vip3price" width="80" />
          <el-table-column label="VIP4价" align="right" prop="vip4price" width="80" />
          <el-table-column label="VIP5价" align="right" prop="vip5price" width="80" />

        </el-table>
        <el-pagination
          v-if="total!==0"
          style="padding-top: 15px;"
          :current-page="pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <el-footer class="el-footerBox">
        <el-row :gutter="24" style="margin-bottom: 10px">
          <el-button v-show="importData.length>0" style="margin-left: 10px" icon="el-icon-refresh-right" type="primary" :loading="updateChecked" @click="updateClick">确认导入</el-button>
        </el-row>
      </el-footer>
      <upload-excel-component ref="upload" :on-success="handleSuccess" :before-upload="beforeUpload" />
    </el-container>
  </div>
</template>

<script>
import { EventBus } from '@/api/eventBus'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { list, upload } from '@/api/product'
import { list as tagList } from '@/api/tag'
export default {
  name: 'product-productExport',
  components: { UploadExcelComponent },
  data() {
    return {
      pageNum: 1,
      pageSize: 20,
      total: 0,
      showError:false,
      curHeight: null,
      tags: [],
      daoruData: '',
      query: {
        date: [],
        isMarketable: '',
        tagIds: ''
      },
      firstSheetName: '',
      importData: [],
      exportData: [],
      showExportData: [],
      updateChecked: false,
      downloadChecked: false,
      pickerOptions: {// 时间快捷选择
        shortcuts: [{
          text: '昨天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created() {
    this.loadTag()
  },
  methods: {
    comeIn() {
      var h = document.documentElement.clientHeight || document.body.clientHeight
      this.curHeight = h - 330// 减去页面上固定高度height
    },
    loadTag() {
      const params = new URLSearchParams()
      params.append('type', '3')
      tagList(params).then(res => {
        this.tags = res.data.data
      })
    },
    updateClick() {
      this.updateChecked = true
      upload(this.showExportData).then(res => {
        res.data.forEach(item=>{
          if (item.result!='success'){
            this.showExportData=res.data
            this.showError=true
          } else  {
            this.updateChecked = false
            EventBus.$emit('scenicspot-productExport', res.data)
            this.$store.dispatch('tagsView/delView', this.$route).then(({ visitedViews }) => {
              this.$router.push({
                path: '/scenicspot/list'
              })
            })// 关闭当前tab回到列表
          }
        })

      }).catch(error=>{
        this.updateChecked = false

        console.log(error)
      })
    },
    handleDownload() { // 导出商品列表
      this.downloadChecked = true
      this.prepareExcel().then(() => {
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['id', '货号',  '品名', '规格1', '规格2', '市场价', '销售价','购物券', '库存', '单位','最小起订量','日限量','VIP1价', 'VIP2价', 'VIP3价', 'VIP4价', 'VIP5价']
          const filterVal = ['id', 'sn',  'name', 'spec1', 'spec2', 'marketPrice', 'price', 'point','stock', 'unit','minLimit','maxLimit','vip1price', 'vip2price', 'vip3price', 'vip4price', 'vip5price']
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '产品列表',
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
        this.downloadChecked = false
      })
    },
    prepareExcel() {
      return new Promise((resolve, reject) => {
        const params = new URLSearchParams()
        if (this.query.date.length > 0) {
          params.append('startDate', this.query.date[0])
          params.append('endDate', this.query.date[1])
        }
        params.append('pageNum', 1)
        params.append('pageSize', 10000)
        params.append('sortField', 'goods')
        params.append('direction', 'asc')
        params.append('isMarketable', this.query.isMarketable)
        params.append('tagIds', this.query.tagIds)
        list(params).then(res => {
          this.exportData = res.data.data
          resolve()
        }).catch(() => { this.downloadChecked = false })
      })
    },
    formatJson(filterVal) {
      return this.exportData.map(v => filterVal.map(j => v[j]))
    },
    daoruClick() {

      this.$refs.upload.handleUpload()
    },
    // 导入表单成功回调事件
    handleSuccess({ results, header, firstSheetName }) {
      this.total = results.length
      this.comeIn()
      this.importData = []
      results.forEach(item => {
        if (item.id != '' || item.id != null) {
          var batchData = {
            id: item.id,
            sn: item.货号,
            supplierName: item.供应商,
            name: item.品名,
            spec1: item.规格1,
            spec2: item.规格2,
            marketPrice: item.市场价,
            price: item.销售价,
            point:item.购物券,
            stock: item.库存,
            unit:item.单位,
            minLimit:item.最小起订量,
            maxLimit:item.日限量,
            vip1price: item.VIP1价,
            vip2price: item.VIP2价,
            vip3price: item.VIP3价,
            vip4price: item.VIP4价,
            vip5price: item.VIP5价
          }
          this.importData.push(batchData)
        }
      })
      this.showExportDataFn(this.pageNum, this.pageSize)
    },
    // //名单导入
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    showExportDataFn(pageNum, pageSize) {
      console.log(this.importData.slice((pageNum - 1) * pageSize, pageNum * pageSize))
      this.showExportData = this.importData.slice((pageNum - 1) * pageSize, pageNum * pageSize)
    },
    handleCurrentChange(value) {
      this.pageNum = value
      this.showExportDataFn(this.pageNum, this.pageSize)
    },
    handleSizeChange(value) {
      this.pageSize = value
      this.showExportDataFn(this.pageNum, this.pageSize)
    }
  }
}
</script>

<style scoped>

</style>
